$(function () {

    // 服务相关信息
    const env = "test"
    let AiHost = ""
    let apiFeedbackPoint = ""
    if (env === "test") {
        AiHost = "http://192.168.10.211:9080/ai"
        apiFeedbackPoint = "http://localhost:7777/api/addInfoPoint"
    } else {
        AiHost = "http://gateway.lsmedia.com/ai"
        apiFeedbackPoint = "http://gateway.lsmedia.com/okr/api/addInfoPoint"
    }


    const isTest = true
    const testToken = "0204d7c5b091394550d8a58afef1e5e1"

    const apiChat = AiHost + "/chat/chat"
    // const apiChat = "http://192.168.10.118:9652/chat"


    const apiAgent = AiHost + "/agent/list"
    const apiEventList = AiHost + "/event/list"
    const apiEventPrompt = AiHost + "/event/solvePrompt"
    const apiCategoryList = AiHost + "/question/categoryList"
    const apiQuestionList = AiHost + "/question/questionList"
    const apiFeedbackQuestionList = AiHost + "/feedback/questionList"
    const apiFeedbackSystemList = AiHost + "/event/systemList"
    const apiFeedbackSubmit = AiHost + "/feedback/feedback"
    const apiChatCallback = AiHost + "/chat/callback"


    let agentId = 0
    let agentName = "Agent"
    let agentList = []



    // 其他相关信息
    let userInfo = {};
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));


    // 会话相关状态
    let isValue = false // 是否输入状态
    let isChat = false // 是否为聊天状态
    let needUpdateHistory = false // 是否更新历史记录
    let chatInfo = {} // 当天会话信息
    let currentChatId = 0; // 当前会话 id
    let lastMsgElement
    let finalContent = "" // 最终内容
    let renderNumber = 0; // 渲染数量
    let tokenNumber = 0; // token 数量
    let globalController; // 全局请求控制
    let chatStatus = 0; // 会话状态
    const chatStatusTimeOut = 1000 * 10 // 会话请求超时接口
    let eventList = {} //  事件信息
    let userMsg = ""
    let startTime = 0
    let userChatId = 0
    let endType = 1


    // 检查登录状态
    if (typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined') {
        checkLogin()
    }

    // 检查登录
    function checkLogin() {
        userInfo = localStorage.getItem("userInfo")
        if (userInfo === null) {
            console.log("未登录")
            chrome.sidePanel.setOptions({ path: "sidebar/login.html", });
        }
        console.log("已登录")
        userInfo = JSON.parse(userInfo)
        console.log(userInfo)
        $("#userName span").text(userInfo.username)
        $("#user-img").attr("src", userInfo.avatar)
        $("#user-img-outer").attr("src", userInfo.avatar)
    }

    // 初始化事件
    initEventList()
    function initEventList() {
        console.log("初始化事件")
        requestEventList().then(function (result) {
            if (result.code !== 0) {
                return
            }
            eventList = result.data.list
            let message = {
                action: 'registerEvent',
                data: eventList
            }
            if (typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined') {
                chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
                    const activeTab = tabs[0];
                    chrome.tabs.sendMessage(activeTab.id, message, function (response) {
                        console.log(response)
                    });
                });
            }
        })
    }

    // 初始化问题
    function initQuestionCategoryList() {
        $(".index-btn").empty();

        requestGet(apiCategoryList + "?agent_id=" + agentId).then(function (result) {
            for (let i = 0; i < result.data.list.length; i++) {
                let btnName = result.data.list[i].name
                let btnId = result.data.list[i].id
                let btn = `<button data-id="${btnId}" type="button" class="btn btn-outline-info btn-sm">${btnName}</button>&nbsp;&nbsp;`
                $(".index-btn").append(btn)

            }
            if (result.data.list.length > 0) {
                renderQuestionList(result.data.list[0].id)
            }
        })
    }

    // 问题点击事件
    $(".index-btn").on("click", ".btn", function () {
        let categoryId = $(this).data("id")
        renderQuestionList(categoryId)
    })

    // 渲染问题列表
    function renderQuestionList(categoryId) {
        let newUrl = apiQuestionList + "&category_id=" + categoryId
        requestGet(newUrl).then(function (result) {
            $(".index-list").empty()
            let questionList = result.data.list
            for (let i = 0; i < questionList.length; i++) {
                let question = questionList[i].question
                let prompt = questionList[i].prompt
                let div = `<div class="index-list-item alert alert-info">${question}
<span style="display:none">${prompt} </span></div>`
                $(".index-list").append(div)
            }
        })
    }

    // 渲染反馈列表
    renderFeedbackQuestionList()
    function renderFeedbackQuestionList() {
        requestGet(apiFeedbackQuestionList).then(function (result) {
            for (let i = 0; i < result.data.data.length; i++) {
                let value = result.data.data[i].id
                let name = result.data.data[i].name
                let div = `<option value="${value}">${name}</option>`
                $("#feedBackSelect").append(div)
            }
        })
    }

    renderFeedbackSystemList()
    function renderFeedbackSystemList() {
        requestGet(apiFeedbackSystemList).then(function (result) {
            for (let i = 0; i < result.data.length; i++) {
                let value = result.data[i].id
                let name = result.data[i].name
                let div = `<option value="${value}">${name}</option>`
                $("#feedBackSystem").append(div)
            }
        })
    }

    // 输入框事件，按钮变色
    $("#chat-input-area").on("input", function () {
        let msg = $(this).val()
        msg = msg.trim()

        if (msg === "") {
            setInputValue(false)
            return
        }

        if (isValue === true) {
            return
        }

        setInputValue(true)
    })

    // 回车输入事件
    $("#chat-input-area").on('keydown', function (event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            sendUserMsg()
        }
    });


    // 点击发送按钮
    $("#chat-input-send-btn").click(function () {
        sendUserMsg()
    })

    // 设置输入状态
    function setInputValue(nowIsValue) {
        if (nowIsValue === false) {
            $("#chat-input-send-btn path").attr("fill", "#cccccc")
        } else {
            $("#chat-input-send-btn path").attr("fill", "#c026d3")
        }
        isValue = nowIsValue
    }

    // 开启新会话
    $("#start-new-btn").click(function () {
        $(".msg-list").empty();
        $(".msg-list").hide();
        $(".index-info").show()

        isChat = false
        setInputValue(false)
        userChatId = 0
    })

    // 右侧菜单点击事件
    $("#sidebar-index").show()
    $(".right-tool-icon").click(function () {
        $(".right-tool-icon").css("background", "#F6F6F8")
        $(this).css("background", "#ffffff")

        let dataType = $(this).data("type")
        if (dataType === "index") {
            $(".sidebar-center").hide()
            $("#sidebar-index").show()
        }

        if (dataType === "feedback") {
            $(".sidebar-center").hide()
            $("#sidebar-feedback").show()
        }

        if (dataType === "agent") {
            $(".sidebar-center").hide()
            $("#sidebar-agent").show()
        }
    })

    $("#feedbackFormSubmit").click(function () {
        let feedbackType = $("#feedBackSelect").val()
        let feedbackSystem = $("#feedBackSystem").val()
        let feedbackQuestion = $("#feedBackInput1").val()
        let feedbackInfo = $("#feedBackInput2").val()
        // myAlert("提交成功","success")
        if (feedbackInfo === "") {
            myAlert("问题概要不能为空", "danger")
            return
        }

        let feedbackPost = {
            feedback_question_id: feedbackType,
            system: feedbackSystem,
            description: feedbackQuestion,
            content: feedbackInfo,
        }

        requestPost(apiFeedbackSubmit, feedbackPost).then(function (result) {
            if (result.code === 0) {
                myAlert("提交成功", "info")

                requestPost(apiFeedbackPoint, { user_id: userInfo.userId }).then(function (result) {
                    if (result.code === 0) {
                        console.log("增加积分成功", userInfo.userId)
                    }
                })
            } else {
                myAlert("提交失败", "danger")
            }
        })


    })

    const myAlert = (message, type) => {
        let alertPlaceholder = document.getElementById('liveAlertPlaceholder')
        $(alertPlaceholder).empty()
        const wrapper = document.createElement('div')
        wrapper.innerHTML = [
            `<div class="my-alert alert alert-${type} alert-dismissible" role="alert">`,
            `   <div>${message}</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('')

        alertPlaceholder.append(wrapper)
        setTimeout(function () {
            $(alertPlaceholder).empty()
        }, 1000)
    }

    async function requestEventList() {
        return requestGet(apiEventList)
    }

    async function requestGet(url) {
        let token = getUserToken()
        try {
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'token': token
                },
                // body: JSON.stringify(msgBody),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            if (data.code === 402) {
                console.log("登录掉线")
                chrome.sidePanel.setOptions({ path: "sidebar/login.html", });
                // checkLogin()
            }
            return data;
        } catch (error) {
            console.error('请求出错:', error);
        }
    }

    async function requestPost(url, postData) {
        let token = getUserToken()
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'token': token
                },
                body: JSON.stringify(postData),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            return data;
        } catch (error) {
            console.error('请求出错:', error);
        }
    }

    // 点击 okr 列表
    $(".index-list").on("click", ".index-list-item", function () {
        let msgInfo = $(this).text().trim()
        sendUserMsg(msgInfo)
    })


    // 停止生成
    $("#stop-signal-btn").click(function () {
        globalController.abort();
        endType = 2;
    })


    // 初始化会话信息
    function initChatInfo() {
        const timestamp = Date.now();

        if (!localStorage.getItem("chatNumber")) {
            localStorage.setItem("chatNumber", "0")
        }

        chatInfo = {
            chatId: 0,
            messageNumber: 0,
            time: timestamp
        };
        currentChatId = parseInt(localStorage.getItem("chatNumber")) + 1
        localStorage.setItem("chatNumber", currentChatId + "")
        chatInfo.chatId = currentChatId

        if (!localStorage.getItem("chatList")) {
            localStorage.setItem("chatList", JSON.stringify([chatInfo]))
        } else {
            let localChatList = localStorage.getItem("chatList")
            let tempChatList = JSON.parse(localChatList)
            tempChatList.push(chatInfo)
            localStorage.setItem("chatList", JSON.stringify(tempChatList))
        }

        isChat = true
        needUpdateHistory = true
    }

    // 发送用户信息
    function sendUserMsg(message = "") {
        let msg = ""
        if (message === "") {
            msg = $("#chat-input-area").val().trim()
        } else {
            msg = message
        }

        if (msg === "") {
            return
        }

        if (isChat === false) {
            initChatInfo();
            $(".index-info").hide()
            $(".msg-list").show()
            $("#stop-signal-btn").attr("disabled", false)
        }

        userMsg = msg
        startTime = Date.now();

        // 追加用户信息
        let msgUserInfo = `<div class="msg-user-info"><span class="alert alert-info"><pre>${msg}</pre></span></div>`
        $(".msg-list").append(msgUserInfo)
        $("#chat-input-area").val("")

        let loading = $(`<div class="spinner-border text-secondary loading" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>`)
        $(".msg-list").append(loading)


        chatInfo.messageNumber++
        storageUserMsg(msg)
        $(".loading").css("display", "block")
        setInputValue(false)

        handleSSE(msg)
    }


    // 获取现在会话信息结构
    function getNowChatMessageBody() {
        let msgBody = {
            // type: seekProviderType,
            // model: seekModel,
            agent_id: agentId,
            messages: []
        }

        for (let i = 0; i <= chatInfo.messageNumber; i++) {
            let userMsgString = localStorage.getItem("chatUserMsg-" + chatInfo.chatId + "-" + i)
            if (userMsgString != null) {
                let userMsgObj = JSON.parse(userMsgString)
                msgBody.messages.push(userMsgObj)
            }
            let assistantMsgString = localStorage.getItem("chatAssistantMsg-" + chatInfo.chatId + "-" + i)
            if (assistantMsgString != null) {
                let assistantMsgObj = JSON.parse(assistantMsgString)
                msgBody.messages.push(assistantMsgObj)
            }
        }

        return msgBody
    }

    // 存储用户会话信息
    function storageUserMsg(msg) {
        let userMsgObj = {
            role: "user",
            content: msg,
            timestamp: Date.now()
        }
        let userMsgString = JSON.stringify(userMsgObj)
        localStorage.setItem("chatUserMsg-" + chatInfo.chatId + "-" + chatInfo.messageNumber, userMsgString)
    }

    $(".history-list").on("click", ".history-info", function () {

        let chatId = $(this).data("id")
        $(".msg-list").empty();
        $(".msg-list").show();
        $(".index-info").hide();


        let chatInfoNumber = parseInt(localStorage.getItem("chatInfoNumber-" + chatId))
        for (let i = 1; i <= chatInfoNumber; i++) {
            let userKey = "chatUserMsg-" + chatId + "-" + i
            let assistantKey = "chatAssistantMsg-" + chatId + "-" + i

            let userString = localStorage.getItem(userKey)
            let assistantString = localStorage.getItem(assistantKey)

            let userObj = JSON.parse(userString)
            let assistantObj = JSON.parse(assistantString)

            let msgUserInfo = `<div class="msg-user-info"><span class="alert alert-info"><pre>${userObj.content}</pre></span></div>`
            $(".msg-list").append(msgUserInfo)

            let assistantContent = marked.parse(assistantObj.content);
            // $(lastMsgElement).children("span").html(htmlChunk);


            let msgChatInfo = $(`<div class="msg-chat-icon">LinQ AI</div><div class="msg-chat-info">
<span class="alert alert-secondary">${assistantContent}</span></div>`);
            $(msgChatInfo).find("span pre code").each(function () {
                hljs.highlightElement(this);
            });
            $(".msg-list").append(msgChatInfo)

        }
        isChat = true
        chatInfo.chatId = chatId
        chatInfo.messageNumber = chatInfoNumber
        $(".msg-list").scrollTop($(".msg-list").prop('scrollHeight'));

    });

    // 选择模型
    $("#agent-list").on("click", ".dropdown-item", function () {
        agentName = $(this).text().trim();
        agentId = $(this).data("id")
        $("#agent-list-btn").text(agentName);
        localStorage.setItem("agentName", agentName);
        localStorage.setItem("agentId", agentId);
        initQuestionCategoryList();
    })

    // $("#provider-list").on("click", ".dropdown-item", function () {
    //     seekProvider = $(this).text().trim();
    //     // let prefixSeekProvider = seekProvider.substr(0,4);
    //     $("#provider-list-btn").text(seekProvider);
    //     localStorage.setItem("seekProvider", seekProvider);
    // })

    // 初始化服务商和模型
    // initProviderModel()
    //
    // function initProviderModel() {
    //     let localSeekProvider = localStorage.getItem("seekProvider");
    //     let localSeekModel = localStorage.getItem("seekModel");
    //     if (localSeekProvider == null) {
    //         localSeekProvider = seekProvider
    //     }
    //     if (localSeekModel == null) {
    //         localSeekModel = seekModel
    //     }
    //     // let prefixLocalSeekProvider = localSeekProvider.substr(0,4);
    //     // let prefixLocalSeekModel = localSeekModel.substr(0,4);
    //     $("#model-list-btn").text(localSeekModel);
    //     $("#provider-list-btn").text(localSeekProvider);
    // }


    // getModelList()
    //
    // function getModelList() {
    //     requestGet(apiModel).then(function (result) {
    //         let providerInfo = result.data[0]
    //         let modelList = providerInfo.model_list
    //         for (let i = 0; i < modelList.length; i++) {
    //             let option = `<li><a class="dropdown-item" href="#">${modelList[i]}</a></li>`
    //             $("#model-list").append(option)
    //         }
    //     });
    // }


    // 获取 AgentList
    getAgentList()
    function getAgentList() {
        requestGet(apiAgent).then(function (result) {
            agentList = result.data.list
            for (let i = 0; i < agentList.length; i++) {
                // 首页 Agent List
                let option = `<li><a class="dropdown-item" href="#" data-id="${agentList[i].id}">${agentList[i].name}</a></li>`
                $("#agent-list").append(option)

                // 侧边栏 Agent List
                let div = `
                    <div class="agent-item">
                        <div class="card" style="width: 100%;">
                            <div class="card-body">
                                <h6 class="card-subtitle mb-2">${agentList[i].name}</h6>
                                <p class="card-text text-muted">${agentList[i].description}</p>
                            </div>
                        </div>
                    </div>
                `
                $("#sidebar-agent-list").append(div)
            }

            // 初始化 Agent
            let localAgentName = localStorage.getItem("agentName");
            let localAgentId = localStorage.getItem("agentId");
            if (localAgentName == null) {
                agentName = agentList[0].name
                agentId = agentList[0].id
                $("#agent-list-btn").text(agentName);
            } else {
                agentId = parseInt(localAgentId)
                $("#agent-list-btn").text(localAgentName);
            }
            initQuestionCategoryList()
        });
    }

    function getUserToken() {
        if (isTest === true) {
            return testToken
        }
        return userInfo.token
    }

    // 渲染历史数据
    renderHistoryList();

    function renderHistoryList() {
        let localChatList = localStorage.getItem("chatList")
        if (localChatList == null) {
            return
        }
        $(".history-list").empty();
        let tempChatList = JSON.parse(localChatList)
        for (let i = 0; i < tempChatList.length; i++) {
            let chatId = tempChatList[i].chatId;
            let userString = localStorage.getItem("chatUserMsg-" + chatId + "-1")
            let assistantString = localStorage.getItem("chatAssistantMsg-" + chatId + "-1")
            let infoTitle, infoChat = ""
            if (userString == null) {
                infoTitle = "";
            } else {
                let userMsgObj = JSON.parse(userString)
                if (userMsgObj) {
                    infoTitle = userMsgObj.content.substr(0, 20) + "..."
                } else {
                    continue;
                }
            }

            if (assistantString == null) {
                infoChat = ""
            } else {
                let assistantMsgObj = JSON.parse(assistantString)
                if (assistantMsgObj.content && assistantMsgObj.content.length > 20) {
                    infoChat = assistantMsgObj.content.substr(0, 20) + "..."
                } else {
                    infoChat = assistantMsgObj.content
                }
            }
            let tempInfo = `
				<div class="history-info " data-id="${chatId}" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom">
					<div class="history-info-title">${infoTitle}</div>
					<div class="history-info-chat">${infoChat}</div>
				</div>
			`
            $(".history-list").append(tempInfo)
        }
        $("#history-number").text("(" + tempChatList.length + ")")
    }


    // 处理流式数据
    async function handleSSE() {
        $(".msg-list").scrollTop($(".msg-list").prop('scrollHeight'));

        let msgBody = getNowChatMessageBody(chatInfo)
        const controller = new AbortController();
        const signal = controller.signal;
        globalController = controller

        // 检查通信状态，超过10s ，主动停止
        chatStatus = 0
        setTimeout(function () {
            if (chatStatus === 0) {
                controller.abort()
                $(".loading").remove();
                $(".loading").css("display", "none");
                let busyInfo = $(`<div class="msg-chat-info"><span class="alert alert-danger">服务繁忙，暂时不可用</span></div>`)
                $(".msg-list").append(busyInfo)
            }
        }, chatStatusTimeOut)

        let token = getUserToken()

        try {
            const response = await fetch(apiChat,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    },
                    body: JSON.stringify(msgBody),
                    signal: signal, // 中断请求
                });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            chatStatus = 1

            // $(".msg-list").scrollTop($(".msg-list").prop('scrollHeight'));
            let loadingClosed = false;

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';
            let lineNumber = 0;
            renderNumber = 0;
            tokenNumber = 0;
            finalContent = "";

            while (true) {
                const { done, value } = await reader.read();

                if (done) {
                    break;
                }

                buffer += decoder.decode(value);
                const messages = buffer.split('\n\n');
                buffer = messages.pop(); // 不能删除，否则会有重复数据

                for (const message of messages) {
                    await new Promise(resolve => setTimeout(resolve, 10));

                    if (message.startsWith('data:')) {

                        const data = message.slice(5).trim();
                        const dataContent = JSON.parse(data)
                        let chunk = dataContent.content

                        if (!loadingClosed) {
                            sseStartHandler()
                            loadingClosed = true;
                        }

                        if (dataContent.content === "[DONE]") {
                            sseDoneHandler()
                            return
                        }

                        //滚动屏幕
                        if (chunk.includes("\n")) {
                            lineNumber++
                            if (lineNumber % 3 === 0) {
                                $(".msg-list").animate({
                                    scrollTop: $(".msg-list").prop('scrollHeight')
                                }, 500);
                                // $(".msg-list").scrollTop($(".msg-list").prop('scrollHeight'));
                            }
                            chunk = chunk.replace(/\n+/g, '\n');
                        }


                        tokenNumber++;
                        finalContent += chunk


                        if (tokenNumber % 5 !== 0) {
                            continue;
                        }


                        renderFinalContent();
                    }
                }
            }
        } catch (error) {
            if (error.name === 'AbortError') {
                console.log('请求已被主动中断');
                $(".loading").remove();
                $(".loading").css("display", "none");
                $("#stop-signal-btn").attr("disabled", true)

                sseDoneHandler()

            } else {
                console.error('请求出错:', error);
            }
        }
    }

    // 渲染数据
    function renderFinalContent() {
        let htmlChunk = marked.parse(finalContent);
        $(lastMsgElement).children("span").html(htmlChunk);
        $(lastMsgElement).find("span pre code").each(function () {
            hljs.highlightElement(this);
        });
        renderNumber++;
    }

    // 流式数据开始
    function sseStartHandler() {
        // 首次接收到数据时关闭 loading 元素
        $(".loading").css("display", "none")
        $(".loading").remove()

        // 添加回答会话框头
        let msgChatIcon = `<div class="msg-chat-icon">LinQ AI</div>`
        $(".msg-list").append(msgChatIcon)

        // 添加回答会话框
        let msgChatInfo = $(`<div class="msg-chat-info"><span class="alert alert-secondary"></span></div>`)
        $(".msg-list").append(msgChatInfo)
        lastMsgElement = msgChatInfo
    }

    // 流式数据结束
    function sseDoneHandler() {
        let assistantMsgObj = {
            role: "assistant",
            content: finalContent,
            timestamp: Date.now()
        }

        let assistantMsgString = JSON.stringify(assistantMsgObj)
        localStorage.setItem("chatAssistantMsg-" + chatInfo.chatId + "-" + chatInfo.messageNumber, assistantMsgString)
        localStorage.setItem("chatInfoNumber-" + chatInfo.chatId, chatInfo.messageNumber + "")


        $(".msg-list").scrollTop($(".msg-list").prop('scrollHeight'));

        if (needUpdateHistory === true) {
            renderHistoryList()
            needUpdateHistory = false
        }

        $("#stop-signal-btn").attr("disabled", true);

        // 最后在渲染一次
        renderFinalContent();

        console.log("渲染次数：", renderNumber)
        console.log("Token 数量：", tokenNumber)
        console.log('流式输出结束');

        let endTime = Date.now();
        let spendTime = endTime - startTime

        let obj = {
            question: userMsg,
            answer: finalContent,
            agent_id: agentId,
            // provider_name: seekProvider,
            // model: seekModel,
            end_type: endType,
            token: tokenNumber,
            time_consume: spendTime,
            parent_id: userChatId
        }
        chatCallBack(obj)
    }

    // 事件处理
    if (typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined') {
        chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {

            // 发送事件内容
            if (message.action === 'sendEventContent') {

                // 切换 Agent id
                if (message.agent_id !== agentId) {
                    for (let i = 0; i < agentList.length; i++) {
                        if (agentList[i].id === message.agent_id) {
                            agentId = message.agent_id
                            $("#agent-list-btn").text(agentList[i].name);
                            initQuestionCategoryList()
                            break
                        }
                    }
                }

                requestPost(apiEventPrompt, message).then(function (result) {
                    if (result.code === 0) {
                        sendUserMsg(result.data.prompt)
                    } else {
                        console.log(result)
                    }
                })
                sendResponse({ code: 0 });
            }

            // 发送用户消息
            // if (message.action === 'sendUserMsg') {
            //     sendUserMsg(message.data)
            //     sendResponse({code: 0});
            // }

            // 通知事件
            if (message.action === 'noticeEvent') {
                initEventList()
            }
            return true;
        });

    } else {
        console.log('当前不是 Chrome 扩展环境，无法监听消息。');
    }

    function chatCallBack(obj) {
        requestPost(apiChatCallback, obj).then(function (result) {
            if (result.code === 0 && userChatId === 0) {
                userChatId = result.data.id
            }
        })
    }
});

